﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SqlServerDriver
{
	public partial class DatabaseFileInfoForm : Form
	{
		public DatabaseFileInfoForm(DataTable fileInfo)
		{
			InitializeComponent();
			this.dgvFileInfo.DataSource = fileInfo;
			// free space width
			this.listPaths.Columns[1].Width = 90;
			// important not to generate the horizontal scroll bar so this
			// takes care of margins etc.
			int fudgeFactor = 25;
			// allocate remaining space to the 1st wide column.
			this.listPaths.Columns[0].Width = this.listPaths.Width - this.listPaths.Columns[1].Width - fudgeFactor;
			// 
			ModifyReport();
		}

		/*
			1. Extract the physical file name from the path as the path can be long and boring
			2. put the path(s) in a separate list at the top
			3. If all of the database files are in the same folder hide the folder info.
		*/
		private void ModifyReport()
		{
			// 1. Extract path info and disk space into the list view
			// 2. hide free disk space and path if all one
			Dictionary<String, int> knownPaths = new Dictionary<String, int>();
			int pathColIndex = 7;
			int freeSpaceColIndex = pathColIndex -1;
			int nameColIndex = 0;
			bool folderIsSame = true;
			foreach (DataGridViewRow row in dgvFileInfo.Rows)
			{
				String freeSpace = row.Cells[freeSpaceColIndex].Value.ToString();
				String filePath = row.Cells[pathColIndex].Value.ToString();
				String fileName = Path.GetFileName(filePath);
				row.Cells[nameColIndex].Value = fileName;
				String folder = Path.GetDirectoryName(filePath);
				if (knownPaths.Count == 0)
				{
					AddPathInfoLine(folder, freeSpace);
					knownPaths.Add(NormalisePath(folder), 1);
				}
				else
				{
					if (!knownPaths.ContainsKey(NormalisePath(folder)))
					{
						folderIsSame = false;
						AddPathInfoLine(folder, freeSpace);
						knownPaths.Add(NormalisePath(folder), 1);
					}
				}
			}
			// hide the folder path (the file name is copied to col 1)
			if (folderIsSame)
				dgvFileInfo.Columns[pathColIndex].Visible = false;
			// hide the disk free space (it's copied to the list view)
			dgvFileInfo.Columns[freeSpaceColIndex].Visible = false;
		}

		private String NormalisePath(String pathName)
		{
			return pathName.Trim().ToUpper();
		}

		private void AddPathInfoLine(String pathName, String freeSpace)
		{
			String[] rowData = new String[2];
			rowData[0] = pathName;
			rowData[1] = freeSpace;

			ListViewItem li = new ListViewItem(rowData);
			//li.Tag = "";
			this.listPaths.Items.Add(li);
		}

		private void BtnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
